<template>
    <div class="container">
        <CustomNav :custom-title="navTitle" theme="light" :onLeftClick="onLeftClick" />
        <Progress :current="currentOrder" :total="totalOrder"></Progress>
        <div class="content">
            <ExamContent :exam-data="examData.data || {}" :current="currentOrder"
                :currentSelectIndex="currentSelectIndex" @on-select="onSelectOptions">
            </ExamContent>
            <div class="btn-proir btn-click" @click="onProirClick">
                上一题
            </div>
        </div>
        <PopupFinish ref="PopupFinishRef" @onSubmit="onSubmit" @onRestart="onRestart" />
    </div>
</template>

<script lang="ts" setup>
const CHANGE_ORDER = {
    INCREATE: 'INCREATE',
    DECREATE: 'DECREATE'
}
type ChangeOrderType = keyof typeof CHANGE_ORDER
const SAVE_DATA = {
    SAVE: 'SAVE',
    SUBMIT: 'SUBMIT'
}
type SaveDataType = keyof typeof SAVE_DATA
import { Ref, ref, onActivated, onDeactivated, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showDialog, showConfirmDialog, showToast } from 'vant';
import CustomNav from '@/pages/components/CustomNav/index.vue'
import Progress from './components/Progress.vue'
import ExamContent from './components/ExamContent.vue'
import PopupFinish from '@/pages/components/PopupFinish/index.vue';
import { utils } from '../../utils';
import { getExamsDetailById, getExamsAnswer, postAnswer, postResult } from '../../api/Home';
import { useAnswerStore } from '../../stores/modules/answer';
const answerStore = useAnswerStore();
const timer = ref<any>(null);
const navTitle = ref<string>('测试中')
const currentGoodId = ref<string | number | null>(null)
const isStartAnswer = ref<boolean>(false)
const examItems = ref<ProjectType.ExamItemProps[]>([])
const PopupFinishRef: Ref<any> = ref(null)
const router = useRouter();
const route = useRoute();
const totalOrder = ref<number>(examItems.value.length || 0)
const answeredArr = ref<ProjectType.QuestionProps[]>([])
const currentOrder = ref<number>(1)
const examType = ref<string>('')
const examData = ref<{ data: ProjectType.ExamItemProps }>({ data: examItems.value[currentOrder.value - 1] || {} })
// 当前选项的index下标
const currentSelectIndex = ref<number | undefined>(undefined)
const onProirClick = () => {
    changeAnswer(CHANGE_ORDER.DECREATE as ChangeOrderType)
}
// 是否完成答题
const isAnswerFinished = computed(() => answeredArr.value.length >= totalOrder.value)
// 点击了导航的返回
const onLeftClick = (goBackFunc: Function) => {
    // 说明没有答完题 就要返回
    if (!isAnswerFinished.value && isStartAnswer.value) {
        showConfirmDialog({
            className: 'custom-dialog-container',
            message: '您的测评还没有完成，确定要现在就离开测评页面吗？',
            confirmButtonColor: '#FA5151',
            cancelButtonColor: '#999999'
        }).then(async () => {
            await postDataToRomate(SAVE_DATA.SAVE as SaveDataType);
        })
    } else {
        goBackFunc && goBackFunc();
    }
}
// 改变答题次序
const changeAnswer = (type: ChangeOrderType) => {
    if (type === CHANGE_ORDER.INCREATE) {
        if (currentOrder.value >= totalOrder.value) {
            return
        }
        currentOrder.value++
    } else {
        if (currentOrder.value <= 1) {
            return
        }
        currentOrder.value--
    }
    // 需要先把 下一题的下标设置为 undefined， 之后异步设置为正确下标 子组件才能监测到下标的变化
    currentSelectIndex.value = undefined
    setExamData()
}
const setExamData = () => {
    setTimeout(() => {
        examData.value.data = examItems.value[currentOrder.value - 1]
        currentSelectIndex.value = computeSelectIndex()
    }, 20);
}
// 选择选项
const onSelectOptions = (data: ProjectType.ExamItemProps) => {
    answeredArr.value[currentOrder.value - 1] = {
        question_id: `${data.details_id}`,
        answer: `${data.currentSelectIndex}`
    }
    answerStore.setAnswerData(answeredArr.value)
    if (isAnswerFinished.value) {
        return PopupFinishRef.value.switchShow(true)
    }
    changeAnswer(CHANGE_ORDER.INCREATE as ChangeOrderType)
}
// 当前选项的index下标
const computeSelectIndex = () => {
    if (!answeredArr.value.length) return undefined
    const currentAnswerObj = answeredArr.value[currentOrder.value - 1] || {}
    if (currentAnswerObj.answer === undefined || currentAnswerObj.answer === null) {
        return undefined
    }
    return +currentAnswerObj.answer
}
// 提交答题答案数据到服务端
const postDataToRomate = async (type: SaveDataType, isExit: boolean = true) => {
    let requestFunc = null, successTip = '';
    if (type === SAVE_DATA.SAVE) {
        requestFunc = postAnswer
    } else {
        requestFunc = postResult
        successTip = '提交成功'
    }
    const { code } = await requestFunc(`${currentGoodId.value}`, answeredArr.value)
    if (!isExit) return
    if (`${code}` === '0') {
        if (successTip) showToast(successTip)
        if (type === SAVE_DATA.SUBMIT) {
            router.replace(`/report/${currentGoodId.value}/${examType.value}`)
        } else {
            utils.goBack(router);
        }
        clearAnswerData();
    } else {
        if (type === SAVE_DATA.SUBMIT) {
            showToast('提交出错，请稍后重试')
            return
        }
        clearAnswerData();
        utils.goBack(router);
    }
}
// 提交答案
const onSubmit = () => {
    postDataToRomate(SAVE_DATA.SUBMIT as SaveDataType)
}
// 重新答题
const onRestart = () => {
    answerStore.clearAnswerData();
    answeredArr.value = [];
    currentOrder.value = 1
    PopupFinishRef.value.switchShow(false);
    setExamData()
}


// 清除答题的答案
const clearAnswerData = () => {
    answerStore.clearAnswerData();
    answeredArr.value = [];
    currentOrder.value = 1
    PopupFinishRef.value.switchShow(false);
    examData.value.data = {}
    examItems.value = []
    isStartAnswer.value = false
    currentGoodId.value = null
    currentSelectIndex.value = undefined
    clearPostAnswersTimer();
}

// 初始化 做完的答案 并且定位当前答题序号
const initAnswersArr = (arr: ProjectType.QuestionProps[]) => {
    answeredArr.value = arr;
    setTimeout(() => {
        if (isAnswerFinished.value) {
            currentOrder.value = arr.length;
        } else {
            currentOrder.value = arr.length + 1;
        }
        // examData.value.data = examItems.value[currentOrder.value - 1]
        setExamData()
    }, 0);
}
const startPostAnswersTimer = () => {
    timer.value = setInterval(() => {
        postDataToRomate(SAVE_DATA.SAVE as SaveDataType, false)
    }, 10000)
}

const clearPostAnswersTimer = () => {
    clearInterval(timer.value)
}

const initData = async () => {
    const { examId, goodId, answerType } = route.params;
    console.log(route.params);

    if (examId !== void 0 && goodId !== void 0) {
        currentGoodId.value = `${goodId}`
        const { code, data } = await getExamsDetailById(`${examId}`)
        if (`${code}` === '0') {
            navTitle.value = data.name!
            examType.value = data.exam_type || ''
            const examItemsRomate = await utils.getJson(`${data.item_url}`)
            examItems.value = examItemsRomate
            totalOrder.value = examItems.value.length
            examData.value.data = examItems.value[currentOrder.value - 1]
            startPostAnswersTimer();
            if (answerStore.answersArr.length) {
                initAnswersArr(answerStore.answersArr)
            } else {
                // 如果是重新答题需要获取原来的答案
                if (answerType === 'restart') {
                    const { code: code1, data: data1 } = await getExamsAnswer(`${goodId}`)
                    if (`${code1}` === '0') {
                        const sameLengthAnswersArr = (data1 || []).slice(0, totalOrder.value)
                        console.log('sameLengthAnswersArr', sameLengthAnswersArr);

                        initAnswersArr(sameLengthAnswersArr)
                        answerStore.setAnswerData(sameLengthAnswersArr);
                    }
                }
            }
            showDialog({
                className: 'custom-dialog-container',
                message: '回答问题时不依据别人眼中的你来判断，而是你认为你本质上是不是这样的，继续看看问题吧。',
            })
            isStartAnswer.value = true
        }
    }
}
onActivated(() => {
    initData();
})
onDeactivated(() => {
    clearAnswerData();
})

</script>

<style lang="scss" scoped>
.container {
    height: 100vh;
    overflow: hidden;
    background-color: $color_bg_grey;
    display: flex;
    flex-direction: column;

    .content {
        padding: 0 15px;
        flex: 1;

        .btn-proir {
            width: 350px;
            height: 50px;
            line-height: 50px;
            text-align: center;
            color: $color_white;
            border-radius: 290px;
            background-color: $color_primary;
            position: fixed;
            bottom: 30px;
            left: 12px;
        }
    }
}
</style>